package com.binbinyl.helper

import android.content.Context
import android.provider.Settings
import android.text.TextUtils
import java.net.NetworkInterface
import java.net.SocketException
import java.util.*


object DeviceUtil {

    fun fetchMyDeviceId(context: Context): String {
        var deviceId = getAndroidId(context)
        if (TextUtils.isEmpty(deviceId)) {
            deviceId = getMac(context)
        }
        deviceId = if (!TextUtils.isEmpty(deviceId)) {
            deviceId.replace(".", "")
        } else {
            val uuid = UUID.randomUUID()
            uuid.toString().replace("-", "")
        }
        return deviceId
    }

    fun getAndroidId(context: Context): String {
        return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID)
    }

    fun getMac(context: Context): String {
        var macAddress = ""
        try {
            val wifiInterfaceName = "wlan0"
            val interfaces = NetworkInterface.getNetworkInterfaces()
            while (interfaces.hasMoreElements()) {
                val iF = interfaces.nextElement()
                if (iF.getName().endsWith(wifiInterfaceName)) {
                    val addr = iF.getHardwareAddress()
                    if (addr == null || addr.size == 0) {
                        return ""
                    }

                    val buf = StringBuilder()
                    for (b in addr) {
                        buf.append(String.format("%02X:", b))
                    }
                    if (buf.length > 0) {
                        buf.deleteCharAt(buf.length - 1)
                    }
                    macAddress = buf.toString()
                    break
                }
            }
        } catch (se: SocketException) {
            macAddress = ""
        }

        if (TextUtils.isEmpty(macAddress)) {
            val wifi = context.getSystemService(Context.WIFI_SERVICE) as android.net.wifi.WifiManager
            macAddress = wifi.connectionInfo.macAddress
        }

        return macAddress
    }
}